package org.apache.ibatis.test.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

/**
 * @author org.org.clxmm
 * @Description
 * @create 2021-07-07 8:12 下午
 */
public class MyBatisUtils {


    private static SqlSessionFactory sqlSessionFactory;

    static {
        try {
            //  初始化sqlSessionFactory对象
            String resource = "org/apache/ibatis/test/mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


    //从 SqlSessionFactory 中获取 SqlSession
    public static SqlSession getSqlSession() {
        // autoCommit 自动提交事物
      System.out.println(sqlSessionFactory == null);
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        return sqlSession;
    }


}
